﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Web;
using System.Threading;

namespace OutSourceingServices.Models.DataAccess
{
    public class XmlProvider : IDataProvider
    {
        private const String APP_DATA_PATH = "\\App_Data\\";
        private const String COMMUNITY_DATA_FILE_EN = "Community.en-US.xml";
        private const String COMMUNITY_DATA_FILE_VN = "Community.vi-VN.xml";

        /// <summary>
        /// Create an instance of XmlProvider type
        /// </summary>
        /// <param name="filePath">Xml file path</param>
        public XmlProvider()
        {
            
        }

        /// <summary>
        /// Load Community data
        /// </summary>
        /// <returns>List of Community object</returns>
        public List<Community> LoadCommunityContent()
        {
            List<Community> lstResult = new List<Community>();

            String strFilePath = Helper.SessionHelper.Culture.TextInfo.CultureName.Equals("en-US") ?
                HttpContext.Current.Server.MapPath(String.Concat(APP_DATA_PATH, COMMUNITY_DATA_FILE_EN)) :
                HttpContext.Current.Server.MapPath(String.Concat(APP_DATA_PATH, COMMUNITY_DATA_FILE_VN));
            XDocument xdocCommunity = XDocument.Load(strFilePath);
            var articles = xdocCommunity.Descendants("Article");
            
            DateTime createdDate;
            Int32 type;          
            // Traverse article list and create result list
            foreach (var item in articles)
            {
                Community community = new Community();
                community.ID = item.Element("ID").Value;
                community.Title = item.Element("Title").Value;
                community.Text = item.Element("Text").Value;
                community.CreatedDate = DateTime.TryParseExact(item.Element("CreatedDate").Value, "dd/mm/yyyy",
                                                                Thread.CurrentThread.CurrentCulture.DateTimeFormat,
                                                                System.Globalization.DateTimeStyles.AssumeLocal,
                                                                out createdDate) ? createdDate : DateTime.MaxValue;
                community.Type = Int32.TryParse(item.Element("Type").Value, out type) ? 
                                (CommunityType)type : 
                                CommunityType.INVALID;
                if (((int)community.Type < 0) || ((int)community.Type > 3))
                {
                    community.Type = CommunityType.INVALID;    
                }

                lstResult.Add(community);
            }

            return lstResult;
        }
    }
}